﻿using Newtonsoft.Json;
using System.Collections.Generic;

namespace Labthink.PCSoft.UniversalHost4.Model
{
    [JsonObject]
    public class PagedList<T> : List<T>
    {
        /// <summary>
        /// 分页编号
        /// </summary>
        [JsonProperty]
        public int PageIndex { get; set; }

        /// <summary>
        /// 分页大小
        /// </summary>
        [JsonProperty]
        public int PageSize { get; set; }

        /// <summary>
        /// 元素总共数目
        /// </summary>
        [JsonProperty]
        public int TotalCount { get; set; }

        /// <summary>
        /// 页数
        /// </summary>
        [JsonProperty]
        public int PageCount { get; set; }

        [JsonProperty]
        public IEnumerable<T> InnerList { get; set; }

        /// <summary>
        /// 默认构造函数用于反序列化
        /// </summary>
        public PagedList()
        {

        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="list">链表</param>
        /// <param name="intPageIndex">编号</param>
        /// <param name="intPageSize">大小</param>
        public PagedList(List<T> list, int intPageIndex, int intPageSize)
        {
            PageIndex = intPageIndex;
            PageSize = intPageSize;

            GetPagedList(list);
        }

        public PagedList(IEnumerable<T> list)
        {
            InnerList = list;
            foreach (T t in list)
            {
                Add(t);
            }
        }

        /// <summary>
        /// 转为为分页
        /// </summary>
        /// <param name="list">链表</param>
        private void GetPagedList(List<T> list)
        {
            int intStart = (PageIndex - 1) * PageSize;

            for (int i = intStart; i < intStart + PageSize && i < list.Count; i++)
            {
                Add(list[i]);
            }


            TotalCount = list.Count;
            if (TotalCount % PageSize == 0)
            {
                PageCount = TotalCount / PageSize;
            }
            else
            {
                PageCount = TotalCount / PageSize + 1;
            }
        }
    }
}
